import Flutter
import UIKit
import Photos
import GalleryFork

public class SwiftPlatformServicePlugin: NSObject, FlutterPlugin {
    var imagePicker: NDImagePicker!
    var scannerPlugin: SwiftNDScannerPlugin!
    
    static var factory:NativeViewFactory?
    
    init(imagePicker: NDImagePicker,scanner:SwiftNDScannerPlugin) {
        self.imagePicker = imagePicker
        scannerPlugin = scanner
        super.init()
    }
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "platform_service", binaryMessenger: registrar.messenger())
        
        let controller = UIApplication.shared.delegate!.window!!.rootViewController!
        let imagePicker = NDImagePicker.init(contro: controller)
        let scanner = SwiftNDScannerPlugin()
        let instance = SwiftPlatformServicePlugin.init(imagePicker: imagePicker, scanner:scanner)
        registrar.addMethodCallDelegate(instance, channel: channel)
        
        // 扫码相关
        let scannerChannel = FlutterMethodChannel(name: "scanner", binaryMessenger: registrar.messenger())
        let scanChannel = FlutterMethodChannel(name: "com.newcore.demo.flutter.plugin/qrcode/file", binaryMessenger: registrar.messenger())
        registrar.addMethodCallDelegate(instance, channel: scannerChannel)
        registrar.addMethodCallDelegate(instance, channel: scanChannel)
        
        if(factory == nil){
            factory = NativeViewFactory(scannerChannel);
        }
        registrar.register(factory!, withId: "com.newcore.demo.flutter.plugin/scanner")
        
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if(call.method == "getPlatformVersion") {
            result("iOS " + UIDevice.current.systemVersion)
        } else if(call.method == "pickImages") {
            imagePicker.setResult(result:result)
            let args = call.arguments as? Dictionary<String, Any>
            let maxCount = args?["maxCount"] as? Int ?? 8
            let enableCamera = args?["enableCamera"] as? Bool ?? false
            imagePicker.startGallery(maxCount: maxCount, enableCamera: enableCamera)
        } else if(call.method == "takePicture") {
            imagePicker.setResult(result:result)
            imagePicker.takePicture()
        } else if(call.method == "start" || call.method == "resume" || call.method == "dispose" || call.method == "stop" || call.method == "pause" || call.method == "ScanImage"){
            scannerPlugin.handle(call: call, result: result)
        } else {
            result(nil)
        }
    }
    
}
